package com.eonmind.ai.service.impl;

import com.eonmind.ai.converts.AiVideoConvert;
import com.eonmind.ai.core.video.model.AiVideoTaskResModel;
import com.eonmind.ai.core.video.platform.enums.AiVideoPlatformEnum;
import com.eonmind.ai.core.video.platform.pixverse.PixVerseService;
import com.eonmind.ai.core.video.platform.pixverse.model.PixverseTaskSubmitReq;
import com.eonmind.ai.dto.AiVideoDto;
import com.eonmind.ai.mapper.AiVideoMapper;
import com.eonmind.ai.service.IAiVideoService;
import com.eonmind.common.contract.data.request.PageRequest;
import com.eonmind.common.contract.data.response.PageResponse;
import com.eonmind.common.contract.data.response.ResponseEntity;
import com.eonmind.common.contract.enums.ai.AiVideoStatusEnum;
import com.eonmind.common.contract.enums.vip.ConsumptionTypeEnum;
import com.eonmind.common.contract.exception.BusinessException;
import com.eonmind.common.provider.dto.VipDto;
import com.eonmind.common.provider.entity.ai.AiVideo;
import com.eonmind.user.contract.dto.UserInfoData;
import com.eonmind.vip.contract.api.VipToAIFeignService;
import com.mongoplus.model.PageResult;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AiVideoService implements IAiVideoService {
    @Resource
    private PixVerseService pixVerseService;
    @Resource
    private AiVideoMapper aiVideoMapper;
    @Autowired
    private VipToAIFeignService vipToAIFeignService;

    @Override
    public AiVideoDto.AiVideoTaskSubmitResponse
    submitVideoTask(UserInfoData userInfoData, AiVideoDto.PixverseTaskSubmitRequest aiVideoTaskSubmitRequest) {
        Integer platform = aiVideoTaskSubmitRequest.getPlatform();
        AiVideoPlatformEnum platformEnum = AiVideoPlatformEnum.getByCode(platform);
        if (platformEnum == null) {
            log.error("平台不存在");
            throw new RuntimeException("平台不存在");
        }
        AiVideoTaskResModel aiVideoTaskResModel = null;
        switch (platformEnum) {
            case PIXVERSE -> {
                PixverseTaskSubmitReq pixverseTaskSubmitReq = new PixverseTaskSubmitReq();
                BeanUtils.copyProperties(aiVideoTaskSubmitRequest, pixverseTaskSubmitReq);
                aiVideoTaskResModel = pixVerseService.submitVideoTask(platformEnum, pixverseTaskSubmitReq);
            }
            default -> {
                log.error("平台不存在");
            }
        }
        if (aiVideoTaskResModel != null && aiVideoTaskResModel.getTaskId() != null) {
            log.info("任务提交成功：{}", aiVideoTaskResModel.getTaskId());
            // 扣减积分
            VipDto.VipBackToAiIsAcResponse vipBackToAiIsAcResponse = decUserCost(userInfoData.getId(), aiVideoTaskSubmitRequest);
            if (!vipBackToAiIsAcResponse.getIsAccess()) {
                throw new BusinessException(vipBackToAiIsAcResponse.getDesc());
            }
            // 保存到数据库
            AiVideo aiVideo = new AiVideo();
            aiVideo.setUserId(userInfoData.getId());
            aiVideo.setPlatformId(platform);
            aiVideo.setPrompt(aiVideoTaskSubmitRequest.getPrompt());
            aiVideo.setRadio(aiVideoTaskSubmitRequest.getRadio());
            aiVideo.setModel(aiVideoTaskSubmitRequest.getModel().name());
            aiVideo.setTaskId(aiVideoTaskResModel.getTaskId());
            aiVideoMapper.save(aiVideo);
            AiVideoDto.AiVideoTaskSubmitResponse aiVideoTaskSubmitResponse = new AiVideoDto.AiVideoTaskSubmitResponse();
            aiVideoTaskSubmitResponse.setVideoId(aiVideo.getId());
            return aiVideoTaskSubmitResponse;
        } else {
            log.error("任务提交失败");
            throw new BusinessException("任务提交失败");
        }
    }

    private VipDto.VipBackToAiIsAcResponse decUserCost(Long userId, AiVideoDto.PixverseTaskSubmitRequest aiVideoTaskSubmitRequest) {
        VipDto.VipAiServerDesc vipAiServerDesc = new VipDto.VipAiServerDesc()
                .setCost(100000)
                .setType(ConsumptionTypeEnum.AI_VIDEO.getCode())
                .setModelId(Long.valueOf(AiVideoPlatformEnum.PIXVERSE.getCode()))
                .setModelName(AiVideoPlatformEnum.PIXVERSE.getName())
                .setUserId(userId);
        ResponseEntity<VipDto.VipBackToAiIsAcResponse> vipBackToAiIsAcResponseResponseEntity = vipToAIFeignService.aiServerIsAc(vipAiServerDesc);
        return vipBackToAiIsAcResponseResponseEntity.getData();
    }

    @Override
    public AiVideoDto.VideoTaskQueryResponse queryVideoTask(UserInfoData userInfoData, AiVideoDto.PixverseTaskQueryRequest aiVideoTaskQueryRequest) {
        AiVideo aiVideo = aiVideoMapper.selectById(aiVideoTaskQueryRequest.getVideoId());
        if (aiVideo != null && ObjectUtils.compare(userInfoData.getId(), aiVideo.getUserId()) == 0) {
            AiVideoDto.VideoTaskQueryResponse aiVideoTaskQueryResponse = new AiVideoDto.VideoTaskQueryResponse();
            BeanUtils.copyProperties(aiVideo, aiVideoTaskQueryResponse);
            Integer status = aiVideoTaskQueryResponse.getStatus();
            AiVideoStatusEnum aiVideoStatusEnum = AiVideoStatusEnum.getByCode(status);
            if (aiVideoStatusEnum != null) {
                aiVideoTaskQueryResponse.setStatusDesc(aiVideoStatusEnum.getDesc());
            }
            return aiVideoTaskQueryResponse;
        } else {
            log.error("任务查询失败");
            throw new BusinessException("任务查询失败");
        }
    }

    @Override
    public PageResponse<AiVideoDto.VideoTaskQueryResponse> pageVideoTask(UserInfoData userInfoData
            , AiVideoDto.VideoTaskPageQueryResponse aiVideoTaskPageQueryRequest) {
        PageResponse<AiVideoDto.VideoTaskQueryResponse> aiVideoTaskPageQueryResponse = new PageResponse<>();
        PageRequest page = aiVideoTaskPageQueryRequest.getPage();
        PageResult<AiVideo> pageResponse = aiVideoMapper.pageVideo(page, userInfoData.getId());
        aiVideoTaskPageQueryResponse.setValue(page, pageResponse.getTotalSize(), AiVideoConvert.toAiVideoTaskQueryResponseList(pageResponse.getContentData()));
        return aiVideoTaskPageQueryResponse;
    }
}
